//
//  RCTBridge+SourceCode.m
//  LBReact
//
//  Created by WuShiHai on 19/6/17.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "RCTImageView+Source.h"
#import "LBReactBridge.h"
#import <React/RCTBridge+Private.h>
#import <React/RCTImageSource.h>

@implementation RCTImageView(Source)

+ (void)load {
    RCTSwapInstanceMethods([RCTImageView class],
                           @selector(setImageSources:),
                           @selector(lb_setImageSources:));
}

- (void)lb_setImageSources:(NSArray<RCTImageSource *> *)imageSources
{
    if (![imageSources isEqual:self.imageSources]) {
        RCTBridge *bridge = [[self valueForKey:@"_bridge"] parentBridge];
        if ([bridge isKindOfClass:[LBBridge class]]) {
            [imageSources enumerateObjectsUsingBlock:^(RCTImageSource * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSURL *URL = obj.request.URL;
                if (URL.isFileURL) {
                    NSURL *redirectURL = [(LBBridge *)bridge URLForAsset:URL];
                    if (redirectURL != URL) {
                        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:redirectURL];
                        request.HTTPBody = obj.request.HTTPBody;
                        request.HTTPMethod = obj.request.HTTPMethod;
                        request.cachePolicy = obj.request.cachePolicy;
                        request.allHTTPHeaderFields = obj.request.allHTTPHeaderFields;
                        [obj setValue:request forKey:@"request"];
                    } else {
                        NSLog(@"%@", URL);
                    }
                }
            }];
        }
        [self lb_setImageSources:imageSources];
    }
}

@end
